package com.chexiehui.jc.ui.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.entity.ForumInfo;
import com.chexiehui.jc.entity.PostInfo;
import com.chexiehui.jc.entity.UserInfo;
import com.chexiehui.jc.event.GlobalFollowSeriesEvent;
import com.chexiehui.jc.event.GlobalFollowUserEvent;
import com.chexiehui.jc.event.GlobalLikePostEvent;
import com.chexiehui.jc.event.GlobalPostAppraiseEvent;
import com.chexiehui.jc.mvp.home.SearchResultAllCovenant;
import com.chexiehui.jc.mvp.home.SearchResultAllPresenter;
import com.chexiehui.jc.ui.activity.CarSeriesDetailsActivity;
import com.chexiehui.jc.ui.activity.ForumDynamicDetailsActivity;
import com.chexiehui.jc.ui.activity.ForumTribuneDetailsActivity;
import com.chexiehui.jc.ui.activity.UserInfoActivity;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NineGridTestLayout;
import com.chexiehui.jc.widget.NoScrollListView;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 搜索综合
 */
public class SearchResultAllFragment extends BaseMvpLazyLoadFragment<SearchResultAllPresenter> implements SearchResultAllCovenant.View {

    @BindView(R.id.nsgv_result_user_grid)
    NonSlidingGridView nsgvResultUserGrid;
    @BindView(R.id.ll_result_user_panel)
    LinearLayout llResultUserPanel;
    @BindView(R.id.nslv_result_post_list)
    NoScrollListView nslvResultPostList;
    @BindView(R.id.ll_result_post_panel)
    LinearLayout llResultPostPanel;
    @BindView(R.id.nsgv_result_forum_grid)
    NonSlidingGridView nsgvResultForumGrid;
    @BindView(R.id.ll_result_forum_panel)
    LinearLayout llResultForumPanel;
    @BindView(R.id.nsgv_result_series_grid)
    NonSlidingGridView nsgvResultSeriesGrid;
    @BindView(R.id.ll_result_series_panel)
    LinearLayout llResultSeriesPanel;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.tv_no_result_user)
    TextView tvNoResultUser;
    @BindView(R.id.tv_no_result_posts)
    TextView tvNoResultPosts;
    @BindView(R.id.tv_no_result_forum)
    TextView tvNoResultForum;
    @BindView(R.id.tv_no_result_series)
    TextView tvNoResultSeries;
    @BindView(R.id.hsv_scroll_user)
    HorizontalScrollView hsvScrollUser;
    @BindView(R.id.hsv_scroll_series)
    HorizontalScrollView hsvScrollSeries;

    private String keyword;
    private List<UserInfo> userList;
    private CommonAdapter<UserInfo> userAdapter;
    private List<PostInfo> postsList;
    private CommonAdapter<PostInfo> postsAdapter;
    private List<ForumInfo> forumList;
    private CommonAdapter<ForumInfo> forumAdapter;
    private List<CarSeriesInfo> seriesList;
    private CommonAdapter<CarSeriesInfo> seriesAdapter;

    public static SearchResultAllFragment getInstance(String keyword) {
        SearchResultAllFragment fragment = new SearchResultAllFragment();
        Bundle bundle = new Bundle();
        bundle.putString("keyword", keyword);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            keyword = bundle.getString("keyword");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_search_result_all;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadingLayout.setStatus(LoadingLayout.Success);
        userList = new ArrayList<>();
        nsgvResultUserGrid.setAdapter(userAdapter = new CommonAdapter<UserInfo>(mActivity, R.layout.item_search_result_user, userList) {
            @Override
            protected void convert(ViewHolder holder, UserInfo item, int position) {
                GlideUtil.loadImageViewCrop(mActivity, item.getPhoto(),
                        holder.getView(R.id.civ_item_avatar), R.drawable.shape_circle, R.drawable.shape_circle);
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_introduce, item.getRemark());
                RadiusTextView rtv_item_follow_action = holder.getView(R.id.rtv_item_follow_action);
                if (item.getId().equals(getUserId())) {
                    rtv_item_follow_action.setVisibility(View.INVISIBLE);
                } else {
                    rtv_item_follow_action.setVisibility(View.VISIBLE);
                    rtv_item_follow_action.setSelected(item.isFollow());
                    rtv_item_follow_action.setText(item.isFollow() ? "取消关注" : "关注");
                    rtv_item_follow_action.setOnClickListener(new NoDoubleClickListener() {
                        @Override
                        public void onNoDoubleClick(View view) {
                            mvpPresenter.doFollowPerson(item.getId());
                        }
                    });
                }
            }
        });
        nsgvResultUserGrid.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivity(UserInfoActivity.class, new BundleBuilder()
                    .putString("userId", userList.get(position).getId())
                    .create());
        });
        postsList = new ArrayList<>();
        nslvResultPostList.setAdapter(postsAdapter = new CommonAdapter<PostInfo>(mActivity, R.layout.item_forum_post, postsList) {
            @Override
            protected void convert(ViewHolder holder, PostInfo item, int position) {
                holder.getView(R.id.tv_item_forum_name).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        startActivity(ForumTribuneDetailsActivity.class, new BundleBuilder()
                                .putString("forumId", item.getForumsId())
                                .create());
                    }
                });
                GlideUtil.loadImageViewCrop(mActivity, item.getAuthorPhoto(), holder.getView(R.id.iv_item_avatar), R.drawable.shape_circle, R.drawable.shape_circle);
                holder.setText(R.id.tv_item_forum_name, item.getForumsName());
                holder.setText(R.id.tv_item_name, item.getAuthorName());
                holder.setText(R.id.tv_item_brief, item.getAuthorRemark());
                TextView tv_item_content = holder.getView(R.id.tv_item_content);
                if (StringUtils.isTrimEmpty(item.getLabel())) {
                    tv_item_content.setText(item.getTitle());
                } else {
                    SpanUtils spanUtils = new SpanUtils();
                    if (item.getLabel().contains("置顶")) {
                        spanUtils.appendImage(R.mipmap.ic_post_zhiding, SpanUtils.ALIGN_BASELINE)
                                .appendSpace(15);
                    }
                    if (item.getLabel().contains("精华")) {
                        spanUtils.appendImage(R.mipmap.ic_post_jinghua, SpanUtils.ALIGN_BASELINE)
                                .appendSpace(15);
                    }
                    spanUtils.append(item.getTitle())
                            .setForegroundColor(ContextCompat.getColor(mActivity, R.color.c_333333))
                            .setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorWhite));
                    tv_item_content.setText(spanUtils.create());
                }
                holder.setText(R.id.tv_item_time, AppCommonUtil.friendlyTime(item.getCreateTime()));
                holder.setText(R.id.tv_item_appraise_count, item.getCommentNum() + "");
                TextView tv_item_follow_count = holder.getView(R.id.tv_item_follow_count);
                tv_item_follow_count.setText(item.getLikenum() + "");
                Drawable drawable1 = getResources().getDrawable(item.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                tv_item_follow_count.setCompoundDrawables(drawable1, null, null, null);
                RadiusTextView rtv_item_follow_action = holder.getView(R.id.rtv_item_follow_action);
                if (item.getAuthorId().equals(getUserId())) {
                    rtv_item_follow_action.setVisibility(View.GONE);
                } else {
                    rtv_item_follow_action.setVisibility(View.VISIBLE);
                    rtv_item_follow_action.setSelected(item.isFollow());
                    rtv_item_follow_action.setText(item.isFollow() ? "取消关注" : "关注");
                    rtv_item_follow_action.setOnClickListener(new NoDoubleClickListener() {
                        @Override
                        public void onNoDoubleClick(View view) {
                            mvpPresenter.doFollowPerson(item.getAuthorId());
                        }
                    });
                }
                tv_item_follow_count.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        mvpPresenter.doDianZan(item.getId());
                    }
                });
                NineGridTestLayout ngtv_item_image_box = holder.getView(R.id.ngtv_item_image_box);
                if (item.getPhotoList().size() > 0) {
                    ngtv_item_image_box.setVisibility(View.VISIBLE);
                    ngtv_item_image_box.setUrlList(item.getPhotoList());
                } else {
                    ngtv_item_image_box.setVisibility(View.GONE);
                }
            }
        });
        nslvResultPostList.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivity(ForumDynamicDetailsActivity.class, new BundleBuilder()
                    .putString("postId", postsList.get(position).getId())
                    .create());
        });
        forumList = new ArrayList<>();
        nsgvResultForumGrid.setAdapter(forumAdapter = new CommonAdapter<ForumInfo>(mActivity, R.layout.item_only_forum, forumList) {
            @Override
            protected void convert(ViewHolder viewHolder, ForumInfo item, int position) {
                RadiusTextView rtv_name = (RadiusTextView) viewHolder.getConvertView();
                rtv_name.setText(item.getName());
            }
        });
        nsgvResultForumGrid.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivity(ForumTribuneDetailsActivity.class, new BundleBuilder()
                    .putString("forumId", forumList.get(position).getId())
                    .create());
        });
        seriesList = new ArrayList<>();
        nsgvResultSeriesGrid.setAdapter(seriesAdapter = new CommonAdapter<CarSeriesInfo>(mActivity, R.layout.item_search_result_series, seriesList) {
            @Override
            protected void convert(ViewHolder holder, CarSeriesInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getImg(), holder.getView(R.id.civ_item_image),
                        R.drawable.shape_square, R.drawable.shape_square);
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_price, item.getPriceMaxMinStr());
                RadiusTextView rtv_item_follow_action = holder.getView(R.id.rtv_item_follow_action);
                rtv_item_follow_action.setVisibility(View.VISIBLE);
                rtv_item_follow_action.setSelected(item.isFollow());
                rtv_item_follow_action.setText(item.isFollow() ? "取消关注" : "关注");
                rtv_item_follow_action.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        mvpPresenter.doFollowSeries(item.getId());
                    }
                });
            }
        });
        nsgvResultSeriesGrid.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivity(CarSeriesDetailsActivity.class,
                    new BundleBuilder().putString("seriesId", seriesList.get(position).getId())
                            .create());
        });

        isPrepared = true;
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isVisible || !isPrepared || mHasLoadedOnce) {
            return;
        }
        mvpPresenter.getUserList();
        mvpPresenter.getPostList();
        mvpPresenter.getForumList();
        mvpPresenter.getSeriesList();
    }

    @Override
    protected SearchResultAllPresenter createPresenter() {
        return new SearchResultAllPresenter(this);
    }

    @Override
    public void onGetUserListSuccess(BaseModel<BasePage<UserInfo>> successResult) {
        mHasLoadedOnce = true;
        tvNoResultUser.setVisibility(View.GONE);
        hsvScrollUser.setVisibility(View.VISIBLE);
        userList.clear();
        userList.addAll(successResult.getData().getItems());
        userAdapter.notifyDataSetChanged();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvResultUserGrid.getLayoutParams();
        lp.width = SizeUtils.dp2px(137) * userList.size() + (userList.size() - 1) * SizeUtils.dp2px(4);
        nsgvResultUserGrid.setLayoutParams(lp);
        nsgvResultUserGrid.setNumColumns(userList.size());
        nsgvResultUserGrid.setColumnWidth(SizeUtils.dp2px(137));
    }

    @Override
    public void onGetUserListFailure(BaseModel<Object> failureResult) {
        mHasLoadedOnce = true;
        tvNoResultUser.setVisibility(View.VISIBLE);
        hsvScrollUser.setVisibility(View.GONE);
        userList.clear();
        userAdapter.notifyDataSetChanged();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvResultUserGrid.getLayoutParams();
        lp.width = SizeUtils.dp2px(137) * userList.size() + (userList.size() - 1) * SizeUtils.dp2px(4);
        nsgvResultUserGrid.setLayoutParams(lp);
        nsgvResultUserGrid.setNumColumns(userList.size());
        nsgvResultUserGrid.setColumnWidth(SizeUtils.dp2px(137));
    }

    @Override
    public void onGetPostListSuccess(BaseModel<BasePage<PostInfo>> successResult) {
        tvNoResultPosts.setVisibility(View.GONE);
        postsList.clear();
        postsList.addAll(successResult.getData().getItems());
        postsAdapter.notifyDataSetChanged();
        nslvResultPostList.setVisibility(View.VISIBLE);
    }

    @Override
    public void onGetPostListFailure(BaseModel<Object> failureResult) {
        tvNoResultPosts.setVisibility(View.VISIBLE);
        nslvResultPostList.setVisibility(View.GONE);
        postsList.clear();
        postsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetForumListSuccess(BaseModel<BasePage<ForumInfo>> successResult) {
        tvNoResultForum.setVisibility(View.GONE);
        nsgvResultForumGrid.setVisibility(View.VISIBLE);
        forumList.clear();
        forumList.addAll(successResult.getData().getItems());
        forumAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetForumListFailure(BaseModel<Object> failureResult) {
        tvNoResultForum.setVisibility(View.VISIBLE);
        nsgvResultForumGrid.setVisibility(View.GONE);
        forumList.clear();
        forumAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetSeriesListSuccess(BaseModel<BasePage<CarSeriesInfo>> successResult) {
        tvNoResultSeries.setVisibility(View.GONE);
        hsvScrollSeries.setVisibility(View.VISIBLE);
        seriesList.clear();
        seriesList.addAll(successResult.getData().getItems());
        seriesAdapter.notifyDataSetChanged();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvResultSeriesGrid.getLayoutParams();
        lp.width = SizeUtils.dp2px(137) * seriesList.size() + (seriesList.size() - 1) * SizeUtils.dp2px(4);
        nsgvResultSeriesGrid.setLayoutParams(lp);
        nsgvResultSeriesGrid.setNumColumns(seriesList.size());
        nsgvResultSeriesGrid.setColumnWidth(SizeUtils.dp2px(137));
    }

    @Override
    public void onGetSeriesListFailure(BaseModel<Object> failureResult) {
        tvNoResultSeries.setVisibility(View.VISIBLE);
        hsvScrollSeries.setVisibility(View.GONE);
        seriesList.clear();
        seriesAdapter.notifyDataSetChanged();
    }

    @Override
    public String getKeyword() {
        return keyword == null ? "" : keyword;
    }

    @Override
    public void onDoDianZanSuccess(BaseModel<String> successResult) {
        for (int i = 0; i < postsList.size(); i++) {
            String id = postsList.get(i).getId();
            if (id.equals(successResult.getData())) {
                EventBus.getDefault().post(new GlobalLikePostEvent(successResult.getData(), !postsList.get(i).isLike()));
                break;
            }
        }
    }

    @Override
    public void onDoDianZanFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoFollowPersonSuccess(BaseModel<String> successResult) {
        boolean isSend = false;
        for (int i = 0; i < postsList.size(); i++) {
            String id = postsList.get(i).getAuthorId();
            if (id.equals(successResult.getData())) {
                isSend = true;
                EventBus.getDefault().post(new GlobalFollowUserEvent(successResult.getData(), !postsList.get(i).isFollow()));
                break;
            }
        }
        if(!isSend){
            for (int i = 0; i < userList.size(); i++) {
                String id = userList.get(i).getId();
                if (id.equals(successResult.getData())) {
                    EventBus.getDefault().post(new GlobalFollowUserEvent(successResult.getData(), !userList.get(i).isFollow()));
                    break;
                }
            }
        }
    }

    @Override
    public void onDoFollowPersonFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoFollowSeriesSuccess(BaseModel<String> successResult) {
        for (int i = 0; i < seriesList.size(); i++) {
            String id = seriesList.get(i).getId();
            if (id.equals(successResult.getData())) {
                EventBus.getDefault().post(new GlobalFollowSeriesEvent(successResult.getData(), !seriesList.get(i).isFollow()));
                break;
            }
        }
    }

    @Override
    public void onDoFollowSeriesFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Subscribe
    public void onGlobalLikePostEvent(GlobalLikePostEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getPostId())) {
            for (int i = 0; i < postsList.size(); i++) {
                String id = postsList.get(i).getId();
                if (id.equals(event.getPostId())) {
                    postsList.get(i).setLike(event.isLiked());
                    postsList.get(i).setLikenum(postsList.get(i).getLikenum() + (event.isLiked() ? 1 : -1));
                    postsAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    @Subscribe
    public void onGlobalPostAppraiseEvent(GlobalPostAppraiseEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getPostId())) {
            for (int i = 0; i < postsList.size(); i++) {
                String id = postsList.get(i).getId();
                if (id.equals(event.getPostId())) {
                    postsList.get(i).setCommentNum(event.getNum());
                    postsAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    @Subscribe
    public void onGlobalFollowUserEvent(GlobalFollowUserEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getUserId())) {
            for (int i = 0; i < postsList.size(); i++) {
                String id = postsList.get(i).getAuthorId();
                if (id.equals(event.getUserId())) {
                    postsList.get(i).setFollow(event.isFollow());
                    postsAdapter.notifyDataSetChanged();
                }
            }
            for (int i = 0; i < userList.size(); i++) {
                String id = userList.get(i).getId();
                if (id.equals(event.getUserId())) {
                    userList.get(i).setFollow(event.isFollow());
                    userAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Subscribe
    public void onGlobalFollowSeriesEvent(GlobalFollowSeriesEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getSeriesId())) {
            for (int i = 0; i < seriesList.size(); i++) {
                String id = seriesList.get(i).getId();
                if (id.equals(event.getSeriesId())) {
                    seriesList.get(i).setFollow(event.isFollow());
                    seriesAdapter.notifyDataSetChanged();
                }
            }
        }
    }
}
